package biz_struct

import (
	"fmt"
	"github.com/gorilla/mux"
	"log"
	"net/http"
)

// web服务器
func CreateWebServer(host string, port int) {
	r := mux.NewRouter()
	r.HandleFunc("/books/{title}/page/{page}", func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		title := vars["title"]
		page := vars["page"]
		fmt.Fprintf(w, "You've requested the book: %s on page %s\n", title, page)
	}).Methods("GET")
	r.HandleFunc("/books/{title}", CreateBook).Methods("POST")
	r.HandleFunc("/books/{title}", ReadBook).Methods("GET")
	r.HandleFunc("/books/{title}", UpdateBook).Methods("PUT")
	r.HandleFunc("/books/{title}", DeleteBook).Methods("DELETE")
	defaultAddr := "localhost:8080"
	if host != "" && port != 0 {
		defaultAddr = host + ":" + fmt.Sprint(port)
	}
	fmt.Println("服务已正常启动:", defaultAddr)
	err := http.ListenAndServe(defaultAddr, r)
	log.Fatalf(err.Error())
}

func DeleteBook(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	title := vars["title"]
	fmt.Fprintln(w, "DeleteBook DELETE", "title:", title)
}

func UpdateBook(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	title := vars["title"]
	fmt.Fprintln(w, "UpdateBook PUT", "title:", title)
}

func ReadBook(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	title := vars["title"]
	fmt.Fprintln(w, "createBook GET", "title:", title)
}

func CreateBook(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	title := vars["title"]
	fmt.Fprintln(w, "createBook POST", "title:", title, "name:")
}

// 创建静态资源
func createStaticResource() {
	fs := http.FileServer(http.Dir("static/"))
	http.Handle("/static/", http.StripPrefix("", fs))
}
